# database/init_db.py
from sqlalchemy import create_engine
from sqlalchemy.orm import sessionmaker
from models import Base, UserInfo, CardInfo, Deposit, TradeInfo
from datetime import datetime, timedelta

# 数据库连接配置
DATABASE_URL = "mysql+pymysql://username:password@localhost:3306/bank_system"
engine = create_engine(DATABASE_URL)
SessionLocal = sessionmaker(autocommit=False, autoflush=False, bind=engine)


def init_database():
    """初始化数据库并插入示例数据"""
    # 创建表
    Base.metadata.create_all(bind=engine)

    db = SessionLocal()
    try:
        # 插入存款类型数据
        deposit_types = [
            {"deposit_type": 1, "deposit_name": "活期", "description": "按存款日结算利息"},
            {"deposit_type": 2, "deposit_name": "定期一年", "description": "存款期是1年"},
            {"deposit_type": 3, "deposit_name": "定期二年", "description": "存款期是2年"},
            {"deposit_type": 4, "deposit_name": "定期三年", "description": "存款期是3年"},
            {"deposit_type": 5, "deposit_name": "定活两便", "description": None},
            {"deposit_type": 6, "deposit_name": "零存整取一年", "description": "存款期是1年"},
            {"deposit_type": 7, "deposit_name": "零存整取二年", "description": "存款期是2年"},
            {"deposit_type": 8, "deposit_name": "零存整取三年", "description": "存款期是3年"},
        ]

        for dt in deposit_types:
            deposit = Deposit(**dt)
            db.add(deposit)

        # 插入用户数据
        user1 = UserInfo(
            username="1010357612345678",
            password="e10adc3949ba59abbe56e057f20f883e",  # 密码: 123456 的MD5哈希
            real_name="张三",
            id_card="210101199001011234",
            phone="13800138001",
            address="北京市海淀区",
            role="customer"
        )

        user2 = UserInfo(
            username="admin",
            password="21232f297a57a5a743894a0e4a801fc3",  # 密码: admin 的MD5哈希
            real_name="管理员",
            id_card="110101198001011234",
            phone="13900139001",
            address="北京市朝阳区",
            role="admin"
        )

        db.add(user1)
        db.add(user2)
        db.commit()

        # 插入银行卡数据
        card1 = CardInfo(
            card_number="1010357612345678",
            user_id=user1.id,
            card_type=1,  # 活期
            balance=12345.67,
            status="normal",
            currency="RMB",
            open_date=datetime.now() - timedelta(days=1000)
        )

        card2 = CardInfo(
            card_number="1010357656781234",
            user_id=user1.id,
            card_type=2,  # 定期一年
            balance=50000.00,
            status="normal",
            currency="RMB",
            open_date=datetime.now() - timedelta(days=180),
            due_date=datetime(2025, 12, 31)
        )

        db.add(card1)
        db.add(card2)
        db.commit()

        # 插入交易记录
        trades = [
            {"card_number": "1010357612345678", "trade_type": "deposit", "amount": 8500.00, "remark": "工资收入"},
            {"card_number": "1010357612345678", "trade_type": "withdraw", "amount": 256.30, "remark": "超市购物"},
            {"card_number": "1010357612345678", "trade_type": "withdraw", "amount": 385.50, "remark": "水电费缴纳"},
            {"card_number": "1010357612345678", "trade_type": "transfer", "amount": 1200.00,
             "other_card": "1010357698765432", "remark": "朋友还款"},
            {"card_number": "1010357654321890", "trade_type": "transfer", "amount": 1200.00,
             "other_card": "1010357612345678", "remark": "朋友借款"},
        ]

        for trade in trades:
            trade_record = TradeInfo(**trade)
            db.add(trade_record)

        db.commit()
        print("数据库初始化成功!")
    except Exception as e:
        db.rollback()
        print(f"数据库初始化失败: {e}")
    finally:
        db.close()


if __name__ == "__main__":
    init_database()